package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Waker
 * @description:
 * @create 2025-09-13-17:12
 */
@Service
public class WechatServiceImpl implements WechatService {
    // 微信登录接口url
    private static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    // 微信获取手机号接口url
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    // 微信获取获取接口调用凭据(access_token)url
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 根据授权码获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        // 1.准备请求数据
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("js_code", code);

        // 2.发起请求
        String result = HttpUtil.get(LOGIN_URL, params);

        // 3.解析返回的JSON格式结果 JSONObject本质是Map
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 4.若错误码有值,抛出业务异常
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }

        // 5.成功返回openId
        return jsonObject.getStr("openid");
    }

    /**
     * 根据手机号授权码获取手机号
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhoneNumber(String phoneCode) {
        // 1.获取access_token
        String accessToken = getAccessToken();
        // 2.准备请求数据
        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);

        // 3.发起请求
        String result = HttpUtil.post(PHONE_URL + accessToken, JSONUtil.toJsonStr(params));

        // 4.解析返回的JSON格式结果 JSONObject本质是Map
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 5.若错误码不为0,抛出业务异常
        if (jsonObject.getInt("errcode") != 0){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }

        // 6.成功返回phoneNumber
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     * 获取access_token
     * @return
     */
    private String getAccessToken() {
        // 1.准备请求数据
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);

        // 2.发起请求
        String result = HttpUtil.get(ACCESS_TOKEN_URL, params);

        // 3.解析返回的JSON格式结果 JSONObject本质是Map
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 4.若错误码有值,抛出业务异常
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }

        // 5.成功返回access_token
        return jsonObject.getStr("access_token");
    }
}
